package com.ganee.agora.viewmodel

import android.app.Application
import android.content.Intent
import androidx.lifecycle.MutableLiveData
import com.alibaba.android.arouter.launcher.ARouter
import com.ganee.agora.model.OriginalLoginRequestBody

import com.ganee.agora.repository.LoginRepository
import com.ganee.baselib.arouter.Constance
import com.ganee.baselib.httprequest.cache.ACache
import com.ganee.baselib.httprequest.cache.EnumKey
import com.ganee.baselib.httprequest.callback.RequestCallback
import com.ganee.baselib.httprequest.callback.RequestMultiplyCallback
import com.ganee.baselib.httprequest.exception.ApiException
import com.ganee.baselib.httprequest.utils.ToastUtil
import com.ganee.baselib.httprequest.utils.Utils
import com.ganee.baselib.mvvmlibrary.base.BaseViewModel
import com.google.gson.Gson
import okhttp3.MediaType

import okhttp3.RequestBody
import org.json.JSONException
import org.json.JSONObject

class LoginViewModel(application: Application) : BaseViewModel<LoginRepository>(application) {

    override fun getRepository(): LoginRepository {
        return LoginRepository(this)
    }

    //接口的请求数据以及回调
    fun login(body: RequestBody) {
        mRepository.login(body, RequestCallback<String> { token ->
            ACache.get(Utils.getContext().applicationContext).put(EnumKey.User.USER_TOKEN, token)
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_MAIN)
                    .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    .navigation()
        })
    }

    //注册
    fun register(account:String,password:String) {
        val requestData = JSONObject()
        try {
            requestData.put("acctNo", account)
            requestData.put("password", password)
            requestData.put("acctType", "03")
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        val requestBody = RequestBody.create(MediaType.parse("application/json"), requestData.toString())
        mRepository.register(requestBody, RequestCallback<Any> {
            val loginBody = OriginalLoginRequestBody(account,password,"03")
            val body = Gson().toJson(loginBody)
            val requestBody = RequestBody.create(MediaType.parse("application/json"), body)
            login(requestBody)
        })
    }
}
